//
//  VertexArray.cpp
//  LearnOpenGL
//
//  Created by Mr.Optimist on 2022/2/10.
//

#include "VertexArray.hpp"
#include "VertexBufferLayout.hpp"
#include <GL/glew.h>

VertexArray::VertexArray() {
    glGenVertexArrays(1, &m_RendererID);   // 生成vertex_array_object
    glBindVertexArray(m_RendererID);       // core模式必须在绑定buffer之前生成并绑定vertex_array_object
}

VertexArray::~VertexArray() {
    glDeleteVertexArrays(1, &m_RendererID);
}

void VertexArray::AddBuffer(const VertexBuffer &vb, const VertexBufferLayout &layout) {
    Bind();         // Bind vertex array
    vb.Bind();      // Bind vertex buffer
    const auto &elements = layout.GetElements();
    unsigned int offset = 0;
    for (unsigned int i = 0; i < elements.size(); i++) {
        const auto &e = elements[i];
        glEnableVertexAttribArray(i);
        glVertexAttribPointer(i, e.count, e.type, e.normalized, layout.GetStride(), (const void *) offset);
        offset += e.count * VertexBufferElement::GetSizeOfType(e.type);
    }
}

void VertexArray::Bind() const {
    glBindVertexArray(m_RendererID);
}

void VertexArray::UnBind() const {
    glBindVertexArray(0);
}

